package com.service.other;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;

import com.service.bean.other.Frame;
import com.service.socket.protocol.Conversion;

public class VersionFile {

	public static final String version_path = "config";
	
	public static List<Frame> getFrames(String version) {
		List<Frame> list = new ArrayList<Frame>();
		try {
			FileInputStream reader = new FileInputStream(version_path + File.separator + version);   
			//BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream()));
			int i = 0;
			int j = 0;
			int n = 1;    
			byte buffer[] = new byte[n];   
			StringBuilder builder = new StringBuilder();
			while ((reader.read(buffer, 0, n) != -1) && (n > 0)){
				if(i==ServerConfig.instance().frame_size){
					Frame f = new Frame();
					f.fileName = Conversion.bytesToHexString(version.getBytes())+"00";
					f.context = builder.toString();
					String size =Integer.toHexString(ServerConfig.instance().frame_size);
					while(size.length()<4){
						size = "0"+size;
					}
					f.size = Conversion.reversal(size);
					String index = Integer.toHexString(j);
					while(index.length()<8){
						index = "0"+index;
					}
					f.index = Conversion.reversal(index);
					list.add(f);
					i = 0;
					j++;
					builder.delete(0, builder.length());
				}
				builder.append(Conversion.bytesToHexString(buffer));
				i++;
			}
			if(builder.length()!=0){
				Frame f = new Frame();
				f.fileName = Conversion.bytesToHexString(version.getBytes())+"00";
				f.context = builder.toString();
				String size = Integer.toHexString(f.context.length() / 2);
				while(size.length()<4){
					size = "0"+size;
				}
				f.size = Conversion.reversal(size);
				String index = Integer.toHexString(j);
				while(index.length()<8){
					index = "0"+index;
				}
				f.index = Conversion.reversal(index);
				list.add(f);
			}
			reader.close();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return list;
	}
}
